package com.erp.gather.listener;

import cn.hutool.core.lang.Dict;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.erp.gather.domain.ErpProductPriceControl;
import com.erp.gather.domain.vo.ErpSellerProductExpandVo;
import com.erp.gather.mapper.*;
import com.erp.gather.service.IErpProductPriceControlService;
import com.esotericsoftware.minlog.Log;
import com.rabbitmq.client.Channel;
import com.ruoyi.auto.api.RemoteAutoPublishProductService;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.utils.JsonUtils;
import com.ruoyi.common.core.utils.SpringUtils;
import com.ruoyi.gather.api.domain.*;
import com.ruoyi.gather.api.domain.dto.AeAutoProductDto;
import com.ruoyi.gather.api.domain.dto.TaskStatusDto;
import com.ruoyi.shop.api.RemoteSellerStoreActivityService;
import com.ruoyi.shop.api.RemoteSellerStorePriceTemplateService;
import com.ruoyi.shop.api.domain.ErpSellerStorePriceTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * 监听路由信息
 *
 * @Author: j.zh
 * @Date: 2024/3/12
 * @Version: 1.0
 **/
@Slf4j
@Component
@RabbitListener(queues = "auto.seller.product.store.queue", ackMode = "MANUAL")
public class AutoSellerStoreProductListener {
    @Resource
    ErpSellerStoreProductMapper baseMapper;
    @Resource
    ErpSellerStoreProductSkuMapper erpSellerStoreProductSkuMapper;
    @Resource
    ErpSellerStoreProductExpandMapper erpSellerStoreProductExpandMapper;
    @Resource
    RemoteSellerStorePriceTemplateService remoteSellerStorePriceTemplateService;
    @Resource
    RemoteSellerStoreActivityService remoteSellerStoreActivityService;
    @Resource
    ErpSellerProductMapper erpSellerProductMapper;
    @Resource
    ErpSellerProductExpandMapper erpSellerProductExpandMapper;
    @Resource
    ErpCollectProductExpandMapper erpCollectProductExpandMapper;
    @Resource
    IErpProductPriceControlService iErpProductPriceControlService;
    @Resource
    RemoteAutoPublishProductService remoteAutoPublishProductService;
    @Resource
    private RabbitTemplate rabbitTemplate = SpringUtils.getBean(RabbitTemplate.class);

    /**
     * 从个人库刊登至在线库
     *
     * @param info
     * @param channel
     * @param message
     * @throws IOException
     */
    @RabbitHandler
    public void listener(String info, Channel channel, Message message) throws IOException {

        try {
            System.out.println("=============接收消息，消息队列开始执行（从个人库刊登至在线库）");
            // 回复队列消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            // 将JSON字符串转换为实体类
            AeAutoProductDto dto = JSONObject.parseObject(info, AeAutoProductDto.class);
            // 执行公共库至个人库操作
            R<Object> resultOne = publishToSellerStoreProduct(dto);
            if (resultOne.getCode() == 500) {
                System.out.println("=============执行失败"+resultOne.getMsg());
            }

        } catch (Exception e) {
            // TODO 消费异常，设置入库操作

            System.out.println("=============执行异常："+ e.toString());
        }

    }

    /**
     * 从个人库刊登至在线库
     *
     * @param dto
     * @return
     */
    @Async("publishToSSPMq")
    public R<Object> publishToSellerStoreProduct(AeAutoProductDto dto) {
        try {
            // 获取个人产品库的商品
            ErpSellerProduct erpSellerProduct = erpSellerProductMapper.selectOne(
                    new LambdaQueryWrapper<ErpSellerProduct>()
                            .eq(ErpSellerProduct::getCollectProductId, dto.getCollectProductId())
                            .eq(ErpSellerProduct::getSellerId, dto.getSellerId())
            );
            if (erpSellerProduct == null) {
                return R.fail("个人商品库中未查找到对应商品");
            }

//            ErpCollectProductExpand expand = erpCollectProductExpandMapper.selectOne(
//                    new LambdaQueryWrapper<ErpCollectProductExpand>()
//                            .eq(ErpCollectProductExpand::getCollectProductId, dto.getCollectProductId())
//            );
            ErpCollectProductExpand expand = dto.getCollectProductExpand();

            Long sellerProductId = erpSellerProduct.getId();

            // 获取个人产品库的商品扩展表
            ErpSellerProductExpandVo productExpandVo = erpSellerProductExpandMapper
                    .selectVoOne(new LambdaQueryWrapper<ErpSellerProductExpand>()
                            .eq(ErpSellerProductExpand::getSellerProductId, sellerProductId));

            Map<String, Object> absoluteQuoteMap = countPrice(
                    expand.getAbsoluteQuoteMap(),
                    dto.getPriceAdjustmentMethod(),
                    dto.getReadjustPricesType(),
                    null,
                    dto.getTemplateId(),
                    dto.getProductPrice()
            );


            // 修改商品价格
            if (Objects.isNull(absoluteQuoteMap)) {
                return R.fail("没有运费试算价格");
            }

            // 保存到店铺在线商品
            ErpSellerStoreProduct sellerStoreProduct = new ErpSellerStoreProduct();
            BeanUtils.copyProperties(erpSellerProduct, sellerStoreProduct);
            sellerStoreProduct.setId(null);
            sellerStoreProduct.setAeProductId(dto.getAeProductId());
            sellerStoreProduct.setSellerProductId(sellerProductId);
            sellerStoreProduct.setStoreId(dto.getStoreId());
            sellerStoreProduct.setStoreUserName(dto.getStoreUserName());
            sellerStoreProduct.setCreateTime(null);
            sellerStoreProduct.setUpdateTime(null);
            sellerStoreProduct.setCreateBy(erpSellerProduct.getSellerId() + "");
            sellerStoreProduct.setUpdateBy(erpSellerProduct.getSellerId() + "");
            sellerStoreProduct.setProductPrice((String) absoluteQuoteMap.get("productPrice"));
            //补充属性
            sellerStoreProduct.setCustomAttributes(dto.getCustomAttributes());
            baseMapper.insert(sellerStoreProduct);

            // 保存店铺在线商品sku
            List<ErpSellerStoreProductSku> erpSellerStoreProductSkuList = dto.getSellerStoreProductSkuList();
            for (ErpSellerStoreProductSku sku : erpSellerStoreProductSkuList) {
                sku.setSellerStoreProductId(sellerStoreProduct.getId());
                sku.setAeProductId(dto.getAeProductId());
                sku.setCreateBy(erpSellerProduct.getSellerId() + "");
                sku.setUpdateBy(erpSellerProduct.getSellerId() + "");

                erpSellerStoreProductSkuMapper.insert(sku);

            }
            // 保存扩展类
            ErpSellerStoreProductExpand erpSellerStoreProductExpand = new ErpSellerStoreProductExpand();
            //保存自动化对应id
            erpSellerStoreProductExpand.setAutoTaskId(Long.valueOf(dto.getAutoTaskId()));
            erpSellerStoreProductExpand.setPriceAdjustmentMethod(dto.getPriceAdjustmentMethod());
            erpSellerStoreProductExpand.setReadjustPricesType(dto.getReadjustPricesType());
            erpSellerStoreProductExpand.setTemplateId(dto.getTemplateId());
            erpSellerStoreProductExpand.setBrandId(dto.getProductBrand());
            erpSellerStoreProductExpand.setActivityId(dto.getActivityId());
            erpSellerStoreProductExpand.setIsAddWatemark(dto.getIsAddWatemark());
            //是否主图调序
            erpSellerStoreProductExpand.setIsMainImageReordering(2);
            //审核状态
            erpSellerStoreProductExpand.setProductStatusType("0");
            erpSellerStoreProductExpand.setPromiseTemplateId(dto.getPromiseTemplateId());
            erpSellerStoreProductExpand.setReduceStrategy(dto.getReduceStrategy());
            erpSellerStoreProductExpand.setFreightTemplateId(dto.getFreightTemplateId());
            erpSellerStoreProductExpand.setSellerStoreProductId(sellerStoreProduct.getId());
            erpSellerStoreProductExpand.setAbsoluteQuoteMap((String) absoluteQuoteMap.get("absoluteQuoteMapStr"));
            //状态设置为发布成功
            erpSellerStoreProductExpand.setStatus(2);
            erpSellerStoreProductExpand.setAeProductId(dto.getAeProductId());
            erpSellerStoreProductExpand.setCreateBy(erpSellerProduct.getSellerId() + "");
            erpSellerStoreProductExpand.setUpdateBy(erpSellerProduct.getSellerId() + "");

            // 设置系统预制运费模板标识，是否自动匹配运费模板，由前端传过来
            erpSellerStoreProductExpand.setSettingFreightTemplateId(productExpandVo.getTemplateId());
            // 查看运费模板是否有多个发货地
            erpSellerStoreProductExpand.setOverseasWarehouse(dto.getShipsFromCountry());
            erpSellerStoreProductExpandMapper.insert(erpSellerStoreProductExpand);


            String msg = dto.getMsg();
            msg = msg + "|从个人库刊登至在线库成功";


            //2、发布商品至营销活动
            R<Object> templateR = remoteSellerStorePriceTemplateService.sellerStorePriceTemplateById(Long.valueOf(dto.getTemplateId()));
            String templateString = JSONObject.toJSONString(templateR.getData());
            ErpSellerStorePriceTemplate priceTemplate = JSONObject.parseObject(templateString, ErpSellerStorePriceTemplate.class);
            if (priceTemplate != null) {
                R<Object> objectR = remoteSellerStoreActivityService.addProductToActivity(sellerStoreProduct.getId(), dto.getActivityId(),
                        priceTemplate.getDiscount());
                Integer status = 2;
                if (objectR.getCode() != 200) {
                    erpSellerStoreProductExpand.setStatus(3);
                    erpSellerStoreProductExpand.setRemark("商品发布成功，活动设置异常");
                    status = 3;
                    msg = msg + "|商品发布成功，活动设置异常";
                } else {
                    msg = msg + "|活动设置完成";
                }
                //返回消息给task任务
                TaskStatusDto taskStatusDto = new TaskStatusDto();
                taskStatusDto.setStatus(status);
                taskStatusDto.setMsg(msg);
                taskStatusDto.setId(dto.getAutoTaskId());
                remoteAutoPublishProductService.updateTaskStatus(taskStatusDto);
            }


//         4.3 分发至gather业务模块，进行上架后的操作
            log.info("开始分发至gather业务模块，进行上架后的操作:" + dto.getCollectProductId());
            rabbitTemplate.convertAndSend("auto-event-exchange", "auto.ae.product.set.data", JSONObject.toJSONString(dto));
            log.info("开始分发至gather业务模块，进行上架后的操作:" + dto.getCollectProductId());

        } catch (Exception e) {
            System.out.println(e.getMessage());
            throw new RuntimeException("发布失败，商品信息有误");
        }
        return R.ok();
    }


    /**
     * @param absoluteQuoteMapStr   区域定价
     * @param priceAdjustmentMethod 调价方式：0固定上调，1百分比上调
     * @param readjustPricesType    手动定价类型（0减去 1加上）
     * @param readjustPrices        调价
     * @param templateId            智能定价模板id
     * @param productPrice          商品价格
     * @return
     */
    public Map<String, Object> countPrice(String absoluteQuoteMapStr, String priceAdjustmentMethod,
                                          Integer readjustPricesType, BigDecimal readjustPrices, String templateId, String productPrice) {
        Map<String, Object> map = new HashMap<>();
        map.put("absoluteQuoteMapStr", absoluteQuoteMapStr);
        map.put("productPrice", productPrice);

        Double min = null;
        Double max = null;

        // 获取是否有个别国家关税调整策略
        Map<String, ErpProductPriceControl> controlMap = iErpProductPriceControlService.getListByType("1"); // 关税

        // 判断调价方式
        if (priceAdjustmentMethod.equals("0")) { // 手动
            // 判断是否为0
            if (readjustPrices.compareTo(BigDecimal.ZERO) == 0)
                return map;
            // 判断上调还是下调
            if (readjustPricesType.equals(0)) // 下调
                readjustPrices = readjustPrices.negate();
            readjustPrices = BigDecimal.ONE
                    .add(readjustPrices.divide(new BigDecimal(100)).setScale(4, BigDecimal.ROUND_HALF_UP));

            map.put("readjustPrices", readjustPrices);

            List<Dict> absoluteQuoteMapList = JsonUtils.parseArrayMap(absoluteQuoteMapStr);
            // 获取运费，修改金额
            for (Dict dict : absoluteQuoteMapList) {
                String shiptoCountry = (String) dict.get("shiptoCountry");
                Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
                for (String key : absoluteQuoteMap.keySet()) {
                    BigDecimal amount = new BigDecimal(absoluteQuoteMap.get(key).toString());
                    amount = amount.multiply(readjustPrices).setScale(2, BigDecimal.ROUND_HALF_UP);

                    Double res = amount.doubleValue();
                    absoluteQuoteMap.put(key, res);
                    if (min == null || res < min)
                        min = res;
                    if (max == null || res > max)
                        max = res;
                }
                // 计算个别国家调价
                absoluteQuoteMap = controlPrice(controlMap, absoluteQuoteMap, shiptoCountry);
            }
            // 获取完成的区域定价
            absoluteQuoteMapStr = JsonUtils.toJsonString(absoluteQuoteMapList);

        } else if (priceAdjustmentMethod.equals("1")) { // 自动

            List<Dict> absoluteQuoteMapList = JsonUtils.parseArrayMap(absoluteQuoteMapStr);

            // 获取模板
            R<Object> priceTemplateObject = remoteSellerStorePriceTemplateService.sellerStorePriceTemplateById(Long.valueOf(templateId));
            if (priceTemplateObject.getCode() != 200) {
                Log.error("未获取到该模版");
                return null;
            }

            String priceTemplateString = JSONObject.toJSONString(priceTemplateObject.getData());
            ErpSellerStorePriceTemplate priceTemplate = JSONObject.parseObject(priceTemplateString, ErpSellerStorePriceTemplate.class);

            //ErpSellerStorePriceTemplate priceTemplate = (ErpSellerStorePriceTemplate) objectR.getData();

            BigDecimal discount = priceTemplate.getDiscount(); // 折扣比例
            BigDecimal union = priceTemplate.getUnion(); // 联盟比例
            BigDecimal transaction = priceTemplate.getTransaction(); // 交易费比例
            BigDecimal profit = priceTemplate.getProfit(); // 预估利润比例
            Integer type = priceTemplate.getType(); // 类型 1标准比例 2最低利润 3固定利润

            BigDecimal oneHundred = new BigDecimal(100);
            BigDecimal proportion = new BigDecimal(100); // 比例
            BigDecimal profitNum = new BigDecimal(100); // 利润值

            if (type.equals(1)) { // 1 标准比例

                profitNum = BigDecimal.ZERO;

                proportion = (BigDecimal.ONE.add(profit.divide(oneHundred)))
                        .divide(BigDecimal.ONE.subtract(union.add(transaction).divide(oneHundred)), 4,
                                BigDecimal.ROUND_HALF_EVEN)
                        .divide(BigDecimal.ONE.subtract(discount.divide(oneHundred)), 4, BigDecimal.ROUND_HALF_EVEN);
            } else if (type.equals(2)) { // 2 最低利润

                // 根据区域定价来确定最低的金额，然后最低的金额获取最低的利润值，就是最低利润

                BigDecimal minAmount = null;

                for (Dict dict : absoluteQuoteMapList) {
                    Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
                    for (String key : absoluteQuoteMap.keySet()) {
                        BigDecimal amount = new BigDecimal(absoluteQuoteMap.get(key).toString());

                        if (minAmount == null) {
                            minAmount = amount;
                        } else {
                            if (minAmount.compareTo(amount) == 1) // 最小值大于本值，就重新赋值
                                minAmount = amount;
                        }
                    }
                }

                // 获取到最小的值，计算利润
                profitNum = minAmount.multiply(profit.divide(oneHundred)).setScale(4, BigDecimal.ROUND_HALF_EVEN);

                // 比例只算联盟、交易、折扣
                proportion = BigDecimal.ONE
                        .divide(BigDecimal.ONE.subtract(union.add(transaction).divide(oneHundred)), 4,
                                BigDecimal.ROUND_HALF_EVEN)
                        .divide(BigDecimal.ONE.subtract(discount.divide(oneHundred)), 4, BigDecimal.ROUND_HALF_EVEN);
            } else if (type.equals(3)) { // 3 固定利润，利润就是传过来的值

                profitNum = profit;

                // 比例只算联盟、交易、折扣
                proportion = BigDecimal.ONE
                        .divide(BigDecimal.ONE.subtract(union.add(transaction).divide(oneHundred)), 4,
                                BigDecimal.ROUND_HALF_EVEN)
                        .divide(BigDecimal.ONE.subtract(discount.divide(oneHundred)), 4, BigDecimal.ROUND_HALF_EVEN);
            }

            map.put("readjustPrices", proportion);
            map.put("profitNum", profitNum);

            // 获取运费，修改金额
            for (Dict dict : absoluteQuoteMapList) {
                String shiptoCountry = (String) dict.get("shiptoCountry");
                Map<String, Object> absoluteQuoteMap = (Map) dict.get("absoluteQuoteMap");
                for (String key : absoluteQuoteMap.keySet()) {
                    BigDecimal amount = new BigDecimal(absoluteQuoteMap.get(key).toString());
                    amount = (amount.add(profitNum)).multiply(proportion).setScale(2, BigDecimal.ROUND_HALF_UP);

                    Double res = amount.doubleValue();
                    absoluteQuoteMap.put(key, res);
                    if (min == null || res < min)
                        min = res;
                    if (max == null || res > max)
                        max = res;
                }
                // 计算个别国家调价
                absoluteQuoteMap = controlPrice(controlMap, absoluteQuoteMap, shiptoCountry);
            }
            // 获取完成的区域定价
            absoluteQuoteMapStr = JsonUtils.toJsonString(absoluteQuoteMapList);
        }

        productPrice = min.equals(max) ? min + "" : min + "-" + max;
        map.put("productPrice", productPrice);
        map.put("absoluteQuoteMapStr", absoluteQuoteMapStr);
        return map;
    }

    /**
     * 计算个别国家调价
     *
     * @param controlMap
     * @param absoluteQuoteMap
     * @param shiptoCountry
     * @return
     */
    private Map<String, Object> controlPrice(Map<String, ErpProductPriceControl> controlMap,
                                             Map<String, Object> absoluteQuoteMap, String shiptoCountry) {

        // 判断该国家是否需要调价
        if (controlMap.containsKey(shiptoCountry)) {

            ErpProductPriceControl control = controlMap.get(shiptoCountry);

            for (String key : absoluteQuoteMap.keySet()) {
                BigDecimal price = new BigDecimal((Double) absoluteQuoteMap.get(key));

                String controlWay = control.getControlWay(); // 调价方式（1固定 2百分比）
                String priceType = control.getPriceType(); // 加减类型 （1加上 2减去）
                BigDecimal amount = new BigDecimal(control.getAmount()); // 价格

                if (controlWay.equals("1")) { // 固定
//					if (priceType.equals("1")) { // 加上
                    price = price.add(amount);
//					} else if (priceType.equals("2")) { // 减去
//						price = price.subtract(amount);
//					}
                } else if (controlWay.equals("2")) { // 百分比
                    BigDecimal subtract = BigDecimal.ONE.subtract(amount.divide(BigDecimal.valueOf(100)));
                    price = price.divide(subtract, 2,
                            BigDecimal.ROUND_HALF_UP);
//					if (priceType.equals("1")) { // 加上
//						price = price.add(amount);
//					} else if (priceType.equals("2")) { // 减去
//						price = price.subtract(amount);
//					}
                }
                Double res = price.doubleValue();
                absoluteQuoteMap.put(key, res);
            }
        }

        return absoluteQuoteMap;
    }
}
